<template>
  <div class="app-container">
    <!-- 筛选条件 -->
    <el-card shadow="never" class="filter-card">
      <div class="filter-container">
        <el-select 
          v-model="collegeId" 
          placeholder="选择学院" 
          clearable
          @change="handleCollegeChange"
          class="filter-item"
        >
          <el-option 
            v-for="college in colleges" 
            :key="college.id" 
            :label="college.name" 
            :value="college.id" 
          />
        </el-select>
        
        <el-select 
          v-model="majorId" 
          placeholder="选择专业" 
          clearable
          @change="handleMajorChange"
          class="filter-item"
          :disabled="!collegeId"
        >
          <el-option 
            v-for="major in majors" 
            :key="major.id" 
            :label="major.name" 
            :value="major.id" 
          />
        </el-select>
        
        <el-select 
          v-model="classId" 
          placeholder="选择班级" 
          clearable
          class="filter-item"
          :disabled="!majorId"
        >
          <el-option 
            v-for="clazz in classes" 
            :key="clazz.id" 
            :label="clazz.name" 
            :value="clazz.id" 
          />
        </el-select>
        
        <el-button 
          type="primary" 
          icon="el-icon-search" 
          @click="fetchData"
          class="filter-item"
        >
          查询
        </el-button>
        
        <el-button 
          type="info" 
          icon="el-icon-refresh" 
          @click="resetFilters"
          class="filter-item"
        >
          重置
        </el-button>
      </div>
    </el-card>

   

    <!-- 数据表格 -->
    <el-card shadow="never" class="table-card">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="6" animated />
      </div>
      <div v-else>
        <div v-if="statisticsData.length === 0 || statisticsData.every(item => item.count === 0)" class="no-data">
          <el-empty description="暂无数据" />
        </div>
        <el-table 
          v-else
          :data="statisticsData" 
          border 
          style="width: 100%"
          :row-class-name="tableRowClassName"
        >
          <el-table-column prop="type" label="人格类型" align="center">
            <template slot-scope="{row}">
              <el-tag :color="getColorForType(row.type)" effect="dark">
                {{ row.type }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="count" label="人数" align="center" />
          <el-table-column label="占比" align="center">
            <template slot-scope="{row}">
              {{ row.percentage }}%
            </template>
          </el-table-column>
          <el-table-column label="比例图" align="center" width="200">
            <template slot-scope="{row}">
              <el-progress 
                :percentage="row.percentage" 
                :color="getProgressColor(row.type)"
                :show-text="false"
              />
              <div class="progress-text">
                <span>{{ row.count }}人 ({{ row.percentage }}%)</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="summary-info">
          <el-tag type="info">总计: {{ totalCount }} 人</el-tag>
          <el-tag type="success">已测试: {{ testedCount }} 人</el-tag>
          <el-tag type="warning">未测试: {{ totalCount - testedCount }} 人</el-tag>
        </div>
      </div>
    </el-card>
  </div>
</template>
<script>
import * as echarts from 'echarts'
import { getColleges } from '@/api/college'
import { getMajorsByCollege } from '@/api/major'
import { getClassesByMajor } from '@/api/class'
import { getPersonalityStatistics } from '@/api/statistics'
import { getStudentCount } from '@/api/student'

// 16种MBTI人格类型
const ALL_PERSONALITY_TYPES = [
  'ISTJ', 'ISFJ', 'INFJ', 'INTJ',
  'ISTP', 'ISFP', 'INFP', 'INTP',
  'ESTP', 'ESFP', 'ENFP', 'ENTP',
  'ESTJ', 'ESFJ', 'ENFJ', 'ENTJ'
]

// 人格类型颜色映射
const PERSONALITY_COLORS = {
  ISTJ: '#5470c6', ISFJ: '#91cc75', INFJ: '#fac858', INTJ: '#ee6666',
  ISTP: '#73c0de', ISFP: '#3ba272', INFP: '#fc8452', INTP: '#9a60b4',
  ESTP: '#ea7ccc', ESFP: '#8dc1a9', ENFP: '#e6d0de', ENTP: '#b6a2de',
  ESTJ: '#d7504b', ESFJ: '#c6e579', ENFJ: '#f4e001', ENTJ: '#f0805a'
}

export default {
  name: 'Statistics',
  data() {
    return {
      // 筛选条件
      collegeId: null,
      majorId: null,
      classId: null,
      
      // 选项数据
      colleges: [],
      majors: [],
      classes: [],
      
      // 统计结果
      statisticsData: [],
      
      // 加载状态
      loading: false,
      
      // 学生总数
      totalCount: 0,
      testedCount: 0,
      
      // ECharts实例
      chart: null
    }
  },
  computed: {
    currentLevel() {
      if (this.classId) return '班级'
      if (this.majorId) return '专业'
      if (this.collegeId) return '学院'
      return '全校'
    }
  },
  mounted() {
    this.initChart()
    this.loadColleges()
    // 这里不立即调用 fetchData，而是在学院加载完成后调用
  },
  methods: {
    // 初始化图表
    initChart() {
  if (!this.$refs.chart) {
    console.warn('图表容器未找到，延迟初始化')
    setTimeout(() => this.initChart(), 500)
    return
  }
  
  // 如果已有实例，先销毁
  if (this.chart) {
    this.chart.dispose()
  }
  
  this.chart = echarts.init(this.$refs.chart)
  
  // 初始设置一个空图表
  const option = {
    title: {
      text: '加载中...',
      left: 'center',
      top: 'center'
    }
  }
  this.chart.setOption(option)
  
  window.addEventListener('resize', () => {
    this.chart && this.chart.resize()
  })
},
    
    // 更新图表数据
    updateChart(data) {
  if (!this.chart) {
    console.error('图表未初始化，无法更新')
    this.initChart()
    setTimeout(() => this.updateChart(data), 300)
    return
  }
  
  // 确保数据是有效的数组
  const chartData = Array.isArray(data) ? data : []
  
  // 构建图表选项
  const option = {
    title: {
      text: `${this.currentLevel}人格分布统计`,
      left: 'center',
      textStyle: {
        fontSize: 18,
        fontWeight: 'bold'
      },
      subtext: `总计: ${this.testedCount}人`,
      subtextStyle: {
        fontSize: 14,
        color: '#666'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}人 ({d}%)'
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: 10,
      top: 60,
      bottom: 20,
      textStyle: {
        fontSize: 12
      }
    },
    series: [
      {
        name: '人格分布',
        type: 'pie',
        radius: ['35%', '65%'],
        center: ['40%', '50%'],
        avoidLabelOverlap: true,
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: chartData.map(item => ({
          value: item.count,
          name: item.type,
          itemStyle: { 
            color: PERSONALITY_COLORS[item.type] || getRandomColor() 
          }
        }))
      }
    ],
    graphic: chartData.length === 0 || chartData.every(d => d.count === 0) ? [{
      type: 'text',
      left: 'center',
      top: 'middle',
      style: {
        text: '暂无数据',
        fill: '#999',
        fontSize: 16
      }
    }] : undefined
  }
  
  // 设置图表选项
  this.chart.setOption(option)
  
  // 强制重绘
  this.chart.resize()
},
    
    async loadColleges() {
      try {
        const res = await getColleges()
        console.log('学院API响应:', res)
        
        // 统一API响应处理
        let data = []
        if (res.data && Array.isArray(res.data)) {
          // 情况1：直接返回数组
          data = res.data
        } else if (res.data && res.data.data && Array.isArray(res.data.data)) {
          // 情况2：返回 { data: [...] } 格式
          data = res.data.data
        } else if (res.data && res.data.code === 1 && Array.isArray(res.data.data)) {
          // 情况3：返回 { code: 1, data: [...] } 格式
          data = res.data.data
        }
        
        // 确保数据有效并过滤掉 null 元素
        this.colleges = data.filter(college => 
          college && college.id && college.name
        )
        
        console.log('加载的学院数据:', this.colleges)
        
        // 学院加载完成后获取数据
        this.fetchData()
      } catch (error) {
        console.error('加载学院数据失败:', error)
        this.$message.error('加载学院数据失败: ' + error.message)
      }
    },
    
    // 加载学生总数
    async loadStudentCount() {
      try {
        const params = {
          collegeId: this.collegeId,
          majorId: this.majorId,
          classId: this.classId
        }
        
        console.log('请求学生统计数据参数:', params)
        const res = await getStudentCount(params)
        console.log('学生统计API响应:', res)
        
        // 统一API响应处理
        let countData = {}
        if (res.data && typeof res.data === 'object') {
          // 情况1：直接返回对象
          countData = res.data
        } else if (res.data && res.data.data && typeof res.data.data === 'object') {
          // 情况2：返回 { data: {...} } 格式
          countData = res.data.data
        } else if (res.data && res.data.code === 1 && typeof res.data.data === 'object') {
          // 情况3：返回 { code: 1, data: {...} } 格式
          countData = res.data.data
        }
        
        this.totalCount = countData.totalCount || 0
        this.testedCount = countData.testedCount || 0
        
        console.log('学生统计结果:', {
          totalCount: this.totalCount,
          testedCount: this.testedCount
        })
      } catch (error) {
        console.error('加载学生数量失败:', error)
        this.totalCount = 0
        this.testedCount = 0
        this.$message.error('加载学生数量失败: ' + error.message)
      }
    },
    
    // 学院变更处理
    async handleCollegeChange(collegeId) {
      this.majorId = null
      this.classId = null
      this.majors = []
      this.classes = []
      
      if (collegeId) {
        try {
          const res = await getMajorsByCollege(collegeId)
          console.log('专业API响应:', res)
          
          // 统一API响应处理
          let data = []
          if (res.data && Array.isArray(res.data)) {
            data = res.data
          } else if (res.data && res.data.data && Array.isArray(res.data.data)) {
            data = res.data.data
          } else if (res.data && res.data.code === 1 && Array.isArray(res.data.data)) {
            data = res.data.data
          }
          
          // 确保数据有效并过滤掉 null 元素
          this.majors = data.filter(major => 
            major && major.id && major.name
          )
          
          console.log('加载的专业数据:', this.majors)
        } catch (error) {
          console.error('加载专业数据失败:', error)
          this.$message.error('加载专业数据失败: ' + error.message)
        }
      }
    },
    
    // 专业变更处理
    async handleMajorChange(majorId) {
      this.classId = null
      this.classes = []
      
      if (majorId) {
        try {
          const res = await getClassesByMajor(majorId)
          console.log('班级API响应:', res)
          
          // 统一API响应处理
          let data = []
          if (res.data && Array.isArray(res.data)) {
            data = res.data
          } else if (res.data && res.data.data && Array.isArray(res.data.data)) {
            data = res.data.data
          } else if (res.data && res.data.code === 1 && Array.isArray(res.data.data)) {
            data = res.data.data
          }
          
          // 确保数据有效并过滤掉 null 元素
          this.classes = data.filter(clazz => 
            clazz && clazz.id && clazz.name
          )
          
          console.log('加载的班级数据:', this.classes)
        } catch (error) {
          console.error('加载班级数据失败:', error)
          this.$message.error('加载班级数据失败: ' + error.message)
        }
      }
    },
    
    // 获取统计数据
    async fetchData() {
  this.loading = true
  try {
    // 1. 加载学生数量
    await this.loadStudentCount()
    
    const params = {
      collegeId: this.collegeId,
      majorId: this.majorId,
      classId: this.classId
    }
    
    const res = await getPersonalityStatistics(params)
    
    // 2. 统一API响应处理
    let statisticsData = []
    if (res.data && Array.isArray(res.data)) {
      statisticsData = res.data
    } else if (res.data && res.data.data && Array.isArray(res.data.data)) {
      statisticsData = res.data.data
    } else if (res.data && res.data.code === 1 && Array.isArray(res.data.data)) {
      statisticsData = res.data.data
    }
    
    // 3. 格式化数据
    this.statisticsData = this.formatStatisticsData(statisticsData)
    
    // 4. 更新图表 - 确保在DOM更新后执行
    this.$nextTick(() => {
      this.updateChart(this.statisticsData)
    })
  } catch (error) {
    console.error('获取统计数据失败:', error)
    this.$message.error('获取统计数据失败: ' + error.message)
    
    // 错误时也更新图表显示错误状态
    this.updateChart([])
  } finally {
    this.loading = false
  }
},
    
    // 重置筛选条件
    resetFilters() {
      this.collegeId = null
      this.majorId = null
      this.classId = null
      this.majors = []
      this.classes = []
      
      // 重置后重新获取数据
      this.fetchData()
    },
    
    // 格式化统计数据
    formatStatisticsData(data) {
      // 确保输入是数组
      if (!Array.isArray(data)) {
        console.warn('formatStatisticsData: 输入数据不是数组', data)
        return ALL_PERSONALITY_TYPES.map(type => ({
          type,
          count: 0,
          percentage: 0.00
        }))
      }
      
      // 创建人格类型映射
      const dataMap = new Map()
      
      data.forEach(item => {
        // 确保item是有效对象且有type属性
        if (item && typeof item === 'object' && item.type) {
          dataMap.set(item.type, item)
        }
      })
      
      // 构建完整数据（包含所有16种类型）
      return ALL_PERSONALITY_TYPES.map(type => {
        if (dataMap.has(type)) {
          const item = dataMap.get(type)
          return {
            type: item.type,
            count: item.count || 0,
            percentage: item.percentage || 0.00
          }
        }
        return {
          type,
          count: 0,
          percentage: 0.00
        }
      }).sort((a, b) => b.count - a.count) // 按数量降序排序
    },
    
    // 获取进度条颜色
    getProgressColor(type) {
      return PERSONALITY_COLORS[type] || '#409EFF'
    },
    
    // 获取人格类型标签颜色
    getColorForType(type) {
      return PERSONALITY_COLORS[type] || '#909399'
    },
    
    // 表格行样式
    tableRowClassName({row}) {
      return row.count === 0 ? 'warning-row' : ''
    }
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
    }
    window.removeEventListener('resize', this.chart.resize)
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.filter-item {
  margin-right: 15px;
  margin-bottom: 10px;
  width: 200px;
}

.chart-card, .table-card {
  margin-bottom: 20px;
}

.loading-container {
  padding: 20px;
}

.no-data {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.progress-text {
  margin-top: 5px;
  font-size: 12px;
  text-align: center;
  color: #666;
}

.summary-info {
  margin-top: 20px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

::v-deep .el-table .warning-row {
  background: #fffbf0;
}
</style>